<!-- 
	输入查询码页面
 -->
<template>
	<view class="container">
		<form @submit="search">
			<view class="form-content">
				<form-item v-for="(item, index) in 5" :key="index" :label="'查询码' + (index + 1)">
					<input placeholder="请输入6位查询码查询码" type="number" maxlength="6" :value="form[index]" @input="customIdInput(index, $event)" />
				</form-item>
			</view>
			<!-- 查询 -->
			<view class="form-action">
				<button type="primary" form-type="submit">查询</button>
			</view>
		</form>
	</view>
</template>

<script>
	import formItem from '@/components/utils-ui/form-item.vue'
	export default {
		components: {
			'form-item': formItem
		},
		data() {
			return {
				form: ['', '', '', '', '']
			}
		},
		mounted() {
			this.getCheckCode()
		},
		methods: {
			customIdInput(index, e) {
				this.$set(this.form, index, e.detail.value)
			},
			// 取出缓存的查询码
			getCheckCode() {
				this.$storage('get', 'checkCode').then(res => {
					try {
						this.form = JSON.parse(res)
					} catch(e) {}
				})
			},
			// 缓存查询码
			setCheckCode() {
				const form = this.form
				this.$storage('set', 'checkCode', JSON.stringify(form)).then(() => {
					this.$store.commit('read-tag/SET_CHECK_CODE', form)
				})
			},
			// 清除查询码的缓存
			clearCheckCode() {				
				this.$storage('remove', 'checkCode').then(() => {
					this.$store.commit('read-tag/SET_CHECK_CODE', [])
				})
			},
			// 查询
			search() {
				let form = this.form
				let pageType = '' // 页面类型
				// 先判断数组思否全部为空
				// 查找第一个不为空的项
				let empty = form.find(id => id != '')
				if(!empty) {
					pageType = 'default'
					this.clearCheckCode() // 清除查询码缓存
				} else {
					pageType = 'code'
					for(let i = 0; i < form.length; i++) {
						if(form[i] != '') {
							if(form[i].length != 6) {
								uni.showToast({
									icon: 'none',
									title: `查询码${i + 1}位数不对！`
								})
								return
							}
						}
					}
					// 非空的判断是否重复
					let noEmpty = form.filter(val => val != '')
					if(new Set(noEmpty).size !== noEmpty.length) {
						uni.showToast({
							icon: 'none',
							title: '输入有重复'
						})
						return false
					}
					this.setCheckCode() // 缓存查询码
				}

				// 设置页面类型
				this.$store.commit('read-tag/SET_PAGE_TYPE', pageType)
				// 查询
				this.$store.dispatch('ble-search/start_bleSearch', 'get')
				// 跳转查询页
				uni.switchTab({
					url: '/pages/read-tag/read-tag',
					animationType: 'slide-in-right'
				})
			}
		}
	}
</script>

<style lang="less" scoped>
@import '../../static/css/form-wrap.less';
</style>
